<template>
  <div class="finance-container">
    <el-card class="page-header">
      <h2>财务统计</h2>
      <p>查看店铺收入、支出和财务报表</p>
    </el-card>

    <!-- 财务概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon revenue">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(todayRevenue) }}</div>
              <div class="stat-label">今日收入</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon orders">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ todayOrders }}</div>
              <div class="stat-label">今日订单</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon monthly">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(monthlyRevenue) }}</div>
              <div class="stat-label">本月收入</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon profit">
              <el-icon><Coin /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ formatMoney(monthlyProfit) }}</div>
              <div class="stat-label">本月利润</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入趋势图表 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>收入趋势</span>
          <el-radio-group v-model="chartPeriod" size="small">
              <el-radio-button value="week">最近7天</el-radio-button>
              <el-radio-button value="month">最近30天</el-radio-button>
              <el-radio-button value="year">最近12个月</el-radio-button>
            </el-radio-group>
        </div>
      </template>
      <div ref="revenueChart" style="height: 400px;"></div>
    </el-card>

    <!-- 财务明细 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>财务明细</span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              @change="handleDateChange"
            />
            <el-button type="primary" size="small" @click="exportData">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="financeList" v-loading="loading">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'income' ? 'success' : 'danger'">
              {{ row.type === 'income' ? '收入' : '支出' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            <span :class="row.type === 'income' ? 'text-success' : 'text-danger'">
              {{ row.type === 'income' ? '+' : '-' }}¥{{ formatMoney(row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="orderId" label="关联订单" width="150">
          <template #default="{ row }">
            <el-link v-if="row.orderId" type="primary" @click="viewOrder(row.orderId)">
              {{ row.orderId }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const chartPeriod = ref('month')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 统计数据
const todayRevenue = ref(2580.50)
const todayOrders = ref(45)
const monthlyRevenue = ref(78650.30)
const monthlyProfit = ref(23595.09)

// 图表引用
const revenueChart = ref(null)
let chartInstance = null

// 财务明细数据
const financeList = ref([
  {
    id: 1,
    date: '2024-01-15',
    type: 'income',
    category: '外卖订单',
    description: '用户订单收入',
    amount: 128.50,
    orderId: 'ORD20240115001'
  },
  {
    id: 2,
    date: '2024-01-15',
    type: 'expense',
    category: '食材采购',
    description: '蔬菜采购',
    amount: 350.00,
    orderId: null
  },
  {
    id: 3,
    date: '2024-01-14',
    type: 'income',
    category: '堂食订单',
    description: '堂食收入',
    amount: 256.80,
    orderId: 'ORD20240114015'
  },
  {
    id: 4,
    date: '2024-01-14',
    type: 'expense',
    category: '平台费用',
    description: '外卖平台佣金',
    amount: 45.20,
    orderId: null
  },
  {
    id: 5,
    date: '2024-01-13',
    type: 'income',
    category: '外卖订单',
    description: '用户订单收入',
    amount: 189.90,
    orderId: 'ORD20240113028'
  }
])

// 格式化金额
const formatMoney = (amount) => {
  return Number(amount).toFixed(2)
}

// 初始化图表
const initChart = () => {
  if (!revenueChart.value) return
  
  chartInstance = echarts.init(revenueChart.value)
  
  const option = {
    title: {
      text: '收入趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        return `${params[0].name}<br/>收入: ¥${params[0].value}`
      }
    },
    xAxis: {
      type: 'category',
      data: ['1月1日', '1月2日', '1月3日', '1月4日', '1月5日', '1月6日', '1月7日']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [{
      data: [1200, 1350, 980, 1580, 1420, 1680, 1850],
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 158, 255, 0.3)'
          }, {
            offset: 1, color: 'rgba(64, 158, 255, 0.1)'
          }]
        }
      }
    }]
  }
  
  chartInstance.setOption(option)
}

// 处理日期范围变化
const handleDateChange = (dates) => {
  console.log('日期范围:', dates)
  loadFinanceData()
}

// 处理分页
const handleSizeChange = (size) => {
  pageSize.value = size
  loadFinanceData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadFinanceData()
}

// 加载财务数据
const loadFinanceData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    total.value = financeList.value.length
    loading.value = false
  }, 500)
}

// 查看订单详情
const viewOrder = (orderId) => {
  ElMessage.info(`查看订单: ${orderId}`)
}

// 导出数据
const exportData = () => {
  ElMessage.success('导出功能开发中...')
}

onMounted(() => {
  nextTick(() => {
    initChart()
  })
  loadFinanceData()
})
</script>

<style lang="scss" scoped>
.finance-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  
  h2 {
    margin: 0 0 8px 0;
    color: #303133;
  }
  
  p {
    margin: 0;
    color: #909399;
  }
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      .el-icon {
        font-size: 24px;
        color: white;
      }
      
      &.revenue {
        background: linear-gradient(135deg, #67C23A, #85CE61);
      }
      
      &.orders {
        background: linear-gradient(135deg, #409EFF, #66B1FF);
      }
      
      &.monthly {
        background: linear-gradient(135deg, #E6A23C, #EEBE77);
      }
      
      &.profit {
        background: linear-gradient(135deg, #F56C6C, #F78989);
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

.chart-card, .table-card {
  margin-bottom: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-actions {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
}

.text-success {
  color: #67C23A;
}

.text-danger {
  color: #F56C6C;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>